package pt.isel.lercm.projectmanager.service;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

import pt.isel.lercm.projectmanager.spring.service.IConstanteService;

public class EmailReceiveService {
	
	private Store store;
	private Folder folder;
	private List<Message> emails;

	private final String mail;
	private final String password;
	
	public EmailReceiveService (IConstanteService constanteService) {
		mail = constanteService.getValorByName("MAIL_ENDERECO");
		password = constanteService.getValorByName("MAIL_PASSWORD");
	}

	
	public void scanNewEmailsFromInbox() throws MessagingException{
		scanEmailsFromInbox(null);
	}
	
	public void scanEmailsFromInboxNum(Integer number) throws MessagingException{
		scanEmailsFromInbox(number);
	}
	
	public void scanAllEmailsFromInbox() throws MessagingException{
		scanEmailsFromInbox(-1);
	}
	
	private void scanEmailsFromInbox(Integer number) throws MessagingException{
		
		Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        
        Session session = Session.getInstance(props, null);
        store = session.getStore();
        store.connect("imap.gmail.com", mail, password);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);
        int n=inbox.getMessageCount();
        
        if (number == null){
        	Flags seen = new Flags(Flags.Flag.SEEN);
            FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            emails = Arrays.asList(inbox.search(unseenFlagTerm));
            return;
        }
        
        if (number == -1){
        	emails = Arrays.asList(inbox.getMessages());
        }
        else{
        	emails = Arrays.asList(inbox.getMessages(n-number,n));
        }
        

	}
	
	public void closeStore() throws MessagingException{
		if (store != null){
			store.close();
		}
	}
	
	public void closeFolder() throws MessagingException{
		if (folder != null){
			folder.close(true);
		}
	}
	
	public void deleteMessage(Message message){
		
	}
	
	public Store getStore() {
		return store;
	}

	public void setStore(Store store) {
		this.store = store;
	}

	public Folder getFolder() {
		return folder;
	}

	public void setFolder(Folder folder) {
		this.folder = folder;
	}

	public List<Message> getEmails() {
		return emails;
	}

	public void setEmails(List<Message> emails) {
		this.emails = emails;
	}
}
